package cn.sylinx.horm.resource.liquor.ext;

import cn.sylinx.horm.config.OrmConfigHolder;
import cn.sylinx.horm.dialect.DbType;
import cn.sylinx.horm.resource.ClasspathSqlResource;
import cn.sylinx.horm.resource.parse.DefaultSqlParser;
import cn.sylinx.horm.resource.parse.SqlParser;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public final class Functions {

    @SuppressWarnings("unchecked")
    public static <T> T ctx(String key) {
        Map<String, Object> context = LiquorContextHolder.get();
        if (context != null) {
            return (T) context.get(key);
        }
        return null;
    }

    public static String foreach_string(Collection<?> input) {
        return foreach(input, "(", ",", ")", "'");
    }

    public static String foreach_string(Collection<?> input, String openSymbolStr, String splitSymbolStr, String closeSymbolStr) {
        return foreach(input, openSymbolStr, splitSymbolStr, closeSymbolStr, "'");
    }

    public static String foreach_number(Collection<?> input) {
        return foreach(input, "(", ",", ")", "");
    }

    public static String foreach_number(Collection<?> input, String openSymbolStr, String splitSymbolStr, String closeSymbolStr) {
        return foreach(input, openSymbolStr, splitSymbolStr, closeSymbolStr, "");
    }

    public static String foreach(Collection<?> input, String openSymbolStr, String splitSymbolStr, String closeSymbolStr, String quote) {
        return ForeachFunctions.foreach(input, openSymbolStr, splitSymbolStr, closeSymbolStr, quote);
    }

    public static String inc_resource(String sqlResource) {

        Map<String, Object> env = LiquorContextHolder.get();
        if (env == null) {
            env = new HashMap<>();
        }
        Object dbtypeObject = env.get(DbType.CURRENT_DB_TYPE);
        DbType dbtype = dbtypeObject == null ? null : DbType.getDbType(dbtypeObject.toString());
        SqlParser sqlParser = new DefaultSqlParser(OrmConfigHolder.getSqlPostfix(), dbtype);
        return sqlParser.parseSqlPart(ClasspathSqlResource.applyLiquorResource(sqlResource), env);
    }
}
